// 时间复杂度: O(n), n 为 k, 空间复杂度 O(1)
export const rotate1 = (nums: number[], k: number): number[] => {
	if (!k || !nums.length) {
		return nums
	}
	k = Math.abs(k % nums.length)
	for (let i = 0; i < k; i++) {
		let n = nums.pop()
		if (n != null) {
			nums.unshift(n)
		}
	}
	return nums
}

// 时间复杂度 O(1), 空间复杂度 O(n), n 为 k
export const rotate2 = (nums: number[], k: number): number[] => {
	if (!k || !nums.length) {
		return nums
	}
	k = Math.abs(k % nums.length)
	let tempArr1 = nums.slice(-k)
	let tempArr2 = nums.slice(0, nums.length - k)
	nums = tempArr1.concat(tempArr2)
	return nums
}

// 功能测试
// const arr = [1, 2, 3, 4, 5, 6, 7]
// const k = 3
// console.log('rotate1: ', rotate1(arr, k))
// console.log('rotate2: ', rotate2(arr, k))

// 性能测试
const arr1 = [],
	arr2 = []
for (let i = 0; i < 100000; i++) {
	arr1.push(i)
	arr2.push(i)
}

// console.time('rotate1')
// for (let i = 0; i < 100000; i++) {
// 	arr1[i] = i
// }
// console.timeEnd('rotate1')

// console.time('rotate2')
// for (let i = 0; i < 100000; i++) {
// 	arr2.unshift(i)
// }
// console.timeEnd('rotate2')

console.time('rotate1')
rotate1(arr1, 90000)
console.timeEnd('rotate1')

console.time('rotate2')
rotate2(arr2, 90000)
console.timeEnd('rotate2')

const arrayRotate = (nums: number[], k: number) => {
	if (k <= 0) {
		return nums
	}

	k = Math.abs(k % nums.length)

	const num1 = nums.slice(k)
	const num2 = nums.slice(0, k)

	return (nums = num1.concat(num2))
}
